{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "NAmA6TjeUzJD"
   },
   "source": [
    "<a href=\"https://colab.research.google.com/github/jeffheaton/app_generative_ai/blob/main/assignments/assignment_yourname_class2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rMtCUtXxZ3ts"
   },
   "source": [
    "# T81-559: Applications of Generative AI\n",
    "* Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/index.html)\n",
    "* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/).\n",
    "\n",
    "**Module 2 Assignment: Code Generation**\n",
    "\n",
    "**Student Name: Your Name**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "s_t8eej3Z3tu"
   },
   "source": [
    "# Assignment Instructions\n",
    "\n",
    "Develop a prompt that will generate an image similar to this one. Your image does not need to look exactly like this one, but important detals, such as the colors, counts, and positions of items are required.  Make sure to also include the prompt as a Python comment string, such as:\n",
    "\n",
    "\"\"\"Prompt: Please write python code to do this.....\"\"\"\n",
    "\n",
    "![Assignment 2](https://s3.amazonaws.com/data.heatonresearch.com/images/wustl/app_genai/assignments/t81_559_assignment_2.jpg)\n",
    "\n",
    "The submit function accepts a PIL image, so it is suggested you use the PIL image library. The idea here is not for you to learn to write Python image rendering, but to have a prompt do the work for you."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vT-h8-JIbVg0"
   },
   "source": [
    "# Google CoLab Instructions\n",
    "\n",
    "If you are using Google CoLab, it will be necessary to mount your GDrive so that you can send your notebook during the submit process.  Running the following code will map your GDrive to ```/content/drive```."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "VDWQvbmRaLLD"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    from google.colab import drive\n",
    "    drive.mount('/content/drive', force_remount=True)\n",
    "    COLAB = True\n",
    "    print(\"Note: using Google CoLab\")\n",
    "except:\n",
    "    print(\"Note: not using Google CoLab\")\n",
    "    COLAB = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RoVl2DQdUzJF"
   },
   "source": [
    "If you are running this notebook with CoLab, the following command will show you your notebooks. You will need to know the location of your notebook when you submit your assignment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "fgb13NXeaif2"
   },
   "outputs": [],
   "source": [
    "!ls /content/drive/My\\ Drive/Colab\\ Notebooks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6vA8pJdpZ3tu"
   },
   "source": [
    "# Assignment Submit Function\n",
    "\n",
    "You will submit the ten programming assignments electronically.  The following **submit** function can be used to do this.  My server will perform a basic check of each assignment and let you know if it sees any underlying problems.\n",
    "\n",
    "**It is unlikely that should need to modify this function.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "IhpWWqjYZ3tv"
   },
   "outputs": [],
   "source": [
    "import base64\n",
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import requests\n",
    "import PIL\n",
    "import PIL.Image\n",
    "import io\n",
    "from io import BytesIO\n",
    "\n",
    "# This function submits an assignment.  You can submit an assignment as much as you like, only the final\n",
    "# submission counts.  The paramaters are as follows:\n",
    "# data - List of pandas dataframes or images.\n",
    "# key - Your student key that was emailed to you.\n",
    "# course - The course that you are in, currently t81-558 or t81-559.\n",
    "# no - The assignment class number, should be 1 through 1.\n",
    "# source_file - The full path to your Python or IPYNB file.  This must have \"_class1\" as part of its name.\n",
    "# .             The number must match your assignment number.  For example \"_class2\" for class assignment #2.\n",
    "def submit(data,key,course,no,source_file=None):\n",
    "    if source_file is None and '__file__' not in globals(): raise Exception('Must specify a filename when a Jupyter notebook.')\n",
    "    if source_file is None: source_file = __file__\n",
    "    suffix = '_class{}'.format(no)\n",
    "    if suffix not in source_file: raise Exception('{} must be part of the filename.'.format(suffix))\n",
    "    with open(source_file, \"rb\") as image_file:\n",
    "        encoded_python = base64.b64encode(image_file.read()).decode('ascii')\n",
    "    ext = os.path.splitext(source_file)[-1].lower()\n",
    "    if ext not in ['.ipynb','.py']: raise Exception(\"Source file is {} must be .py or .ipynb\".format(ext))\n",
    "    payload = []\n",
    "    for item in data:\n",
    "        if type(item) is PIL.Image.Image:\n",
    "            buffered = BytesIO()\n",
    "            item.save(buffered, format=\"PNG\")\n",
    "            payload.append({'PNG':base64.b64encode(buffered.getvalue()).decode('ascii')})\n",
    "        elif type(item) is pd.core.frame.DataFrame:\n",
    "            payload.append({'CSV':base64.b64encode(item.to_csv(index=False).encode('ascii')).decode(\"ascii\")})\n",
    "    r= requests.post(\"https://api.heatonresearch.com/wu/submit\",\n",
    "        headers={'x-api-key':key}, json={ 'payload': payload,'assignment': no, 'course':course, 'ext':ext, 'py':encoded_python})\n",
    "    if r.status_code==200:\n",
    "        print(\"Success: {}\".format(r.text))\n",
    "    else: print(\"Failure: {}\".format(r.text))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "id": "cwHjhzzgZ3ty",
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "source": [
    "# Assignment #2 Sample Code\n",
    "\n",
    "For assignment #2 I will give you starting code that renders the wrong sort of image, however, it goes through all the necessary steps. The first step is to develop a prompt, such as:\n",
    "\n",
    "```\n",
    "Write a Python program that draws a 600x600 image, with a 8-pointed white star with a black background, the star should be hollow, with a line-width of 7. Use PIL to render it.\n",
    "```\n",
    "\n",
    "Then use chatgpt-5o-mini to create the code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "-OvkF33bZ3t9"
   },
   "outputs": [],
   "source": [
    "'''Prompt: Write a Python program that draws a 600x600 image, with a 8-pointed\n",
    "white star with a black background, the star should be hollow, with a line-width\n",
    "of 7. Use PIL to render it.\n",
    "'''\n",
    "\n",
    "from PIL import Image, ImageDraw\n",
    "import math\n",
    "\n",
    "# Function to draw an 8-pointed star\n",
    "def draw_star(draw, center, radius, color, line_width):\n",
    "    points = []\n",
    "    for i in range(16):  # 16 points needed for an 8-pointed star\n",
    "        angle = math.pi / 8 * i  # Calculate the angle\n",
    "        r = radius if i % 2 == 0 else radius / 2  # Alternate between outer and inner points\n",
    "        x = center[0] + r * math.cos(angle)\n",
    "        y = center[1] + r * math.sin(angle)\n",
    "        points.append((x, y))\n",
    "\n",
    "    draw.polygon(points, outline=color, width=line_width)\n",
    "\n",
    "# Create a black background image\n",
    "image_size = (600, 600)\n",
    "image = Image.new(\"RGB\", image_size, \"black\")\n",
    "draw = ImageDraw.Draw(image)\n",
    "\n",
    "# Define the star parameters\n",
    "center = (300, 300)\n",
    "radius = 200\n",
    "color = \"white\"\n",
    "line_width = 7\n",
    "\n",
    "# Draw the 8-pointed star\n",
    "draw_star(draw, center, radius, color, line_width)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8FRx-wD16w_R"
   },
   "source": [
    "Quick code to render what you drew."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "qVwH4noNZxRe"
   },
   "outputs": [],
   "source": [
    "# Display the image using matplotlib\n",
    "plt.imshow(image)\n",
    "plt.axis('off')  # Hide the axes\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "CewIj1T1ZgMf"
   },
   "outputs": [],
   "source": [
    "# This is your student key that I emailed to you at the beginnning of the semester.\n",
    "key = \"Gx5en9cEVvaZnjhdaushddhuhhO4PsI32sgldAXj\"  # This is an example key and will not work.\n",
    "\n",
    "# You must also identify your source file.  (modify for your local setup)\n",
    "file='/content/drive/MyDrive/Colab Notebooks/assignment_yourname_class2.ipynb'  # Google CoLab\n",
    "# file='C:\\\\Users\\\\jeffh\\\\projects\\\\t81_559_deep_learning\\\\assignments\\\\assignment_yourname_class2.ipynb'  # Windows\n",
    "# file='/Users/jheaton/projects/t81_559_deep_learning/assignments/assignment_yourname_class2.ipynb'  # Mac/Linux\n",
    "\n",
    "#df = pd.DataFrame({'a' : [0, 0, 1, 1], 'b' : [0, 1, 0, 1], 'c' : [0, 1, 1, 0]})\n",
    "\n",
    "#submit(source_file=file,data=[df],key=key,course='t81-559',no=1)\n",
    "\n",
    "submit(source_file=file,data=[image],key=key,no=2, course='t81-559')"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3.11 (genai)",
   "language": "python",
   "name": "genai"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
